package com.mfy.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

public class GlobleExceptionHanler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        Map<String, String> result = new HashMap<>();
        //1.获取相应对象
        ServerHttpResponse response = exchange.getResponse();

        //2.response是否结束 多个异常处理时候
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        //2.设置响应头类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        //3.设置响应状态码
        if (ex instanceof IllegalTokenException){
            response.setStatusCode(HttpStatus.FORBIDDEN);
        }else {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return response
                .writeWith(Mono.fromSupplier(()->{
                    DataBufferFactory bufferFactory = response.bufferFactory();
                    result.put("msg",ex.getMessage());
                    ObjectMapper objectMapper = new ObjectMapper();
                    try{
                        return bufferFactory.wrap(objectMapper.writeValueAsBytes(result));
                    }catch (JsonProcessingException e){
                        e.printStackTrace();
                        return null;
                    }
                }));
    }
}
